﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System.Text;
using Backend.Packets;
using Backend;

namespace GameServer.Backend
{
    public class GameClient
    {
        private TcpClient m_Client;

        private NetworkStream m_Stream;

        private short m_nClientID;

        private string m_sUserName;

        private bool m_bLoggedIn;

        private byte[] m_RecvBuffer;

        private PacketParser m_Parser;

        private IDataStream m_DataStream;

        public bool LoggedIn
        {
            get
            {
                return m_bLoggedIn;
            }
            set
            {
                m_bLoggedIn = value;
            }
        }

        public string UserName
        {
            get
            {
                return m_sUserName;
            }
            set
            {
                m_sUserName = value;
            }
        }

        public GameClient(short ClientID, TcpClient Client)
        {
            m_nClientID = ClientID;
            m_Client = Client;

            m_DataStream = new DataStream();
            m_DataStream.OnPacket += new Action<byte[]>(m_DataStream_OnPacket);

            m_Parser = new PacketParser(this);

            m_Stream = Client.GetStream();

            m_RecvBuffer = new byte[1024];

            m_Stream.BeginRead(m_RecvBuffer, 0, m_RecvBuffer.Length, OnRecv, null);
        }

        void m_DataStream_OnPacket(byte[] obj)
        {
            m_Parser.ParsePacket(obj);
        }

        public void Send(IPacket Packet)
        {
            m_Stream.Write(Packet.Pack(), 0, Packet.Length);
        }

        private void OnRecv(IAsyncResult Ar)
        {
            try
            {
                int nBytesRead = m_Stream.EndRead(Ar);

                m_DataStream.Parse(m_RecvBuffer, nBytesRead);

                m_Stream.BeginRead(m_RecvBuffer, 0, m_RecvBuffer.Length, OnRecv, null);
            }
            catch (Exception Ex)
            {
                //System.Windows.Forms.MessageBox.Show(Ex.Message + "\r\n" + Ex.StackTrace);
                GameServer.GetInstance().ClientDC(this);
            }
        }
    }
}
